package com.fool
{
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;

	public class Player implements ISerializable 
	{
		protected var _name:String;
		
		[Bindable]
		public var source:ArrayCollection = new ArrayCollection();
		
		public function Player(name:String)
		{
			this._name = name;
		}
		
		public function get name():String
		{
			return _name;
		}

		public function get necessaryCardsCount():uint
		{
			var count:int = Enum.BALANCE_COUNT - source.length;
			if(count < 0)
			{
				count = 0;
			}
			return count;
		}
		public function recive(cards:ArrayCollection):void
		{
			source.addAll(cards); //TODO: concat or user << game.getCards(count)
			defineSort(source); //descending suit -> rank
		}
		
		public function resetHighlits():void 
		{
			for each (var card:Card in source) 
			{
				card.enabled = true;				
			}
		}
		
		private function defineSort(collection:ArrayCollection):void
		{
			var sort:Sort = new Sort();//sort_by {|f| File.basename f}
			//descending all
			sort.fields = [ 
				new SortField("suit", false, true, true),  
				new SortField("rank", false, true, true) 
			];
			
			collection.sort = sort;
			collection.refresh();
		}
		
		public function getCard(card:Card):Card
		{
			var index:int = source.getItemIndex(card);//TODO: in Ryby:var index:int = player.indexOf(target);
			return source.removeItemAt(index) as Card; //player.splice(index, 1);
		}
		
		public function putAll(cards:ArrayCollection):void
		{
			source.addAll(cards);
			//TODO:reset highliths
		}
		

		public function highlithAttackingCards(tableCards:Array):void
		{
			for each (var item:Card in source) 
			{
				item.enabled = isEqualRank(tableCards, item);
			}
		}
		
		public function getCardWithMinValue():Card
		{
			var allCards:Array = source.source.concat();
			return getCardWithLowestValue(allCards);
		}
		
		protected function getCardWithLowestValue(cards:Array):Card
		{
			cards.sortOn("value", Array.NUMERIC);
			return cards[0] as Card;
		}
		
		public function get empty():Boolean
		{
			return Util.isEmpty(source);
		}
		
		protected function isEqualRank(tableCards:Array, item:Card):Boolean {
			for each (var card:Card in tableCards) 
			{
				if (card.rank == item.rank)
					return true
			}
			return false; 
		}
		
		public function deSerialize(value:String):void
		{
			function populate(element:*, index:int, arr:Array):Card {
				var data:Array = element.split(Enum.CARD_DELEMETER);
				var rank:uint = data[0];
				var suit:uint = data[1];
				return new Card(rank, suit);
			}
			
			source.removeAll();
			var records:Array = value.split(Enum.SEQUENCE_DELIMITER);
			source = new ArrayCollection( records.map(populate) );
		}
		
		public function serialize():String
		{
			return source.source.join(Enum.SEQUENCE_DELIMITER); //getID
		}
	}
}